'use client';

import React, { useState, useRef, useEffect, useMemo, useCallback } from 'react';
import { PlayInfo } from '@/lib/utils/types';
import HtmlLink from '@/app/components/common/html-link';
import { createPortal } from 'react-dom';
import { useGridColumns } from '@/app/hooks/use-columns';

interface MobilePlaylistProps {
  videoId: number;
  playList: PlayInfo[];
  currentPlayIndex?: number;
  onEpisodeChange?: (index: number) => void;
}

export default function MobilePlaylist({ videoId, playList, currentPlayIndex = 0, onEpisodeChange }: MobilePlaylistProps) {
  const [isDrawerOpen, setIsDrawerOpen] = useState(false);
  const [activeGroup, setActiveGroup] = useState<string | null>(null);
  const [isReversed, setIsReversed] = useState(false);
  const [shouldScroll, setShouldScroll] = useState(true); const [isFromSort, setIsFromSort] = useState(false);
  const [localCurrentIndex, setLocalCurrentIndex] = useState(currentPlayIndex);
  const drawerRef = useRef<HTMLDivElement>(null);
  const scrollContainerRef = useRef<HTMLDivElement>(null);
  const activeItemRef = useRef<HTMLAnchorElement>(null);
  const groupTabsRef = useRef<HTMLDivElement>(null);
  const activeGroupTabRef = useRef<HTMLButtonElement>(null);

  // 防止组件挂载前尝试访问document
  const [isMounted, setIsMounted] = useState(false);
  const drawerContentRef = useRef<HTMLDivElement>(null);

  // 计算视频总集数
  const totalEpisodes = playList.length;

  // 获取排序后的播放列表
  const sortedPlayList = useMemo(() => {
    const sorted = [...playList];
    if (isReversed) {
      return sorted.reverse();
    }
    return sorted;
  }, [playList, isReversed]);

  // 将选集分组，按每50集分为一组 - 使用useMemo优化
  const groupedPlaylist = useMemo(() => {
    const grouped: { [key: string]: PlayInfo[] } = {};
    sortedPlayList.forEach((item, index) => {
      const groupKey = `${Math.floor(index / 50) * 50 + 1}-${Math.min((Math.floor(index / 50) + 1) * 50, totalEpisodes)}`;
      if (!grouped[groupKey]) {
        grouped[groupKey] = [];
      }
      grouped[groupKey].push(item);
    });
    return grouped;
  }, [sortedPlayList, totalEpisodes]);

  // 计算当前显示的一组选集
  const currentGroupEpisodes = useMemo(() => {
    return activeGroup ? groupedPlaylist[activeGroup] : sortedPlayList.slice(0, 50);
  }, [activeGroup, groupedPlaylist, sortedPlayList]);

  // 使用自定义钩子计算网格列数
  const gridCols = useGridColumns(drawerContentRef, currentGroupEpisodes, playList);

  useEffect(() => {
    setIsMounted(true);

    return () => {
      // 组件卸载时确保恢复body样式
      if (document.body) {
        document.body.style.overflow = '';
      }
    };
  }, []);

  // 滚动高亮分页按钮到容器中间
  const scrollActiveGroupToCenter = useCallback(() => {
    if (activeGroupTabRef.current && groupTabsRef.current) {
      const tabsContainer = groupTabsRef.current;
      const activeTab = activeGroupTabRef.current;
      
      // 计算需要滚动的位置使当前标签居中
      const containerWidth = tabsContainer.offsetWidth;
      const tabWidth = activeTab.offsetWidth;
      const tabLeft = activeTab.offsetLeft;
      const scrollLeft = tabLeft - (containerWidth / 2) + (tabWidth / 2);
      
      // 如果计算的滚动位置有效，则执行滚动
      if (!isNaN(scrollLeft) && isFinite(scrollLeft) && scrollLeft >= 0) {
        tabsContainer.scrollTo({
          left: scrollLeft,
          behavior: 'smooth'
        });
      }
    }
  }, []);

  // 使用一个ref来跟踪用户是否手动选择了分组
  const userSelectedGroup = useRef(false);

  // 确保当前选中的组是激活的
  useEffect(() => {
    // 如果用户已手动选择分组，则不自动切换
    if (userSelectedGroup.current) return;
    
    if (localCurrentIndex !== undefined && Object.keys(groupedPlaylist).length > 0) {
      // 计算在排序后列表中的索引位置
      let sortedIndex = localCurrentIndex;
      if (isReversed) {
        sortedIndex = playList.length - 1 - localCurrentIndex;
      }
      
      // 计算分组索引
      const groupIndex = Math.floor(sortedIndex / 50);
      const groupKeys = Object.keys(groupedPlaylist);
      if (groupKeys.length > 0 && groupIndex < groupKeys.length) {
        const groupKey = groupKeys[groupIndex];
        // 只在组件初始化或播放索引变化时设置activeGroup
        if (!activeGroup) {
          setActiveGroup(groupKey);
          
          // 在下一帧滚动高亮按钮到可视区域中间
          requestAnimationFrame(() => {
            scrollActiveGroupToCenter();
          });
        }
      }
    }
  }, [localCurrentIndex, groupedPlaylist, isReversed, playList.length, activeGroup, scrollActiveGroupToCenter]);
  
  // 当activeGroup变化时，滚动到活动分页
  useEffect(() => {
    if (isMounted && activeGroup) {
      // 设置一个标志用于调试
      console.log('activeGroup变化:', activeGroup);
      
      // 延迟执行，确保DOM已更新
      setTimeout(() => {
        scrollActiveGroupToCenter();
      }, 100);
    }
  }, [activeGroup, isMounted, scrollActiveGroupToCenter]);

  // 当props中的currentPlayIndex变化时，更新本地状态
  useEffect(() => {
    setLocalCurrentIndex(currentPlayIndex);
  }, [currentPlayIndex]);

  // 首次加载时立即滚动到选中集数
  useEffect(() => {
    if (isMounted && activeItemRef.current && scrollContainerRef.current) {
      // 立即执行滚动操作
      const container = scrollContainerRef.current;
      const item = activeItemRef.current;
      if (container && item) {
        const containerWidth = container.offsetWidth;
        const itemWidth = item.offsetWidth;
        const itemLeft = item.getBoundingClientRect().left;
        const containerLeft = container.getBoundingClientRect().left;
        const relativePosition = itemLeft - containerLeft;
        const scrollLeft = container.scrollLeft + relativePosition - (containerWidth / 2) + (itemWidth / 2);

        if (!isNaN(scrollLeft) && scrollLeft >= 0) {
          // 使用立即滚动，不使用平滑效果
          container.scrollTo({ left: scrollLeft });
          console.log('首次加载立即滚动到选中选集:', localCurrentIndex);
        }
      }
    }
  }, [isMounted, playList]); // 只在组件挂载时和播放列表变化时执行一次

  // 使用useCallback优化事件处理函数
  const openDrawer = useCallback(() => {
    setIsDrawerOpen(true);

    // 抽屉打开时，重置用户选择标志，确保显示当前播放集数所在分组
    userSelectedGroup.current = false;
    
    // 根据当前选中的选集，打开对应的分组
    if (currentPlayIndex !== undefined) {
      // 计算在排序后列表中的索引位置
      let sortedIndex = currentPlayIndex;
      if (isReversed) {
        sortedIndex = playList.length - 1 - currentPlayIndex;
      }
      
      // 计算分组索引
      const groupIndex = Math.floor(sortedIndex / 50);
      const groupKeys = Object.keys(groupedPlaylist);
      if (groupKeys.length > 0 && groupIndex < groupKeys.length) {
        const groupKey = groupKeys[groupIndex];
        // 每次抽屉打开时都设置为当前播放集数所在分组
        setActiveGroup(groupKey);
        console.log('抽屉打开，设置分组为:', groupKey);
      }
    }

    // 禁止背景滚动
    if (document.body) {
      document.body.style.overflow = 'hidden';
    }
  }, [currentPlayIndex, groupedPlaylist, isReversed, playList.length]);

  const closeDrawer = useCallback(() => {
    setIsDrawerOpen(false);

    // 关闭抽屉时保留当前活动分组状态
    // 但在下次打开时会重新设置为当前播放集数所在分组

    // 恢复背景滚动
    if (document.body) {
      document.body.style.overflow = '';
    }
  }, []);

  // 处理选集点击
  const handleEpisodeClick = useCallback((index: number) => {
    // 首先更新本地状态
    setLocalCurrentIndex(index);

    // 使用 history API 直接修改 URL，不触发页面跳转
    const newUrl = `/detail/${videoId}-${index}.html`;
    window.history.pushState({ path: newUrl }, '', newUrl);

    // 通知父组件选集已更改
    onEpisodeChange?.(index);

    // 派发自定义事件通知播放器切换播放源
    if (typeof window !== 'undefined') {
      const episode = playList[index];
      if (episode && episode.url) {
        console.log('移动端切换选集:', index, episode.url);

        // 确保事件详情包含完整信息
        const eventDetail = {
          url: episode.url,
          name: episode.name,
          index: index
        };

        // 使用更明确的事件派发方式
        const event = new CustomEvent('switchEpisode', {
          detail: eventDetail,
          bubbles: true,
          cancelable: true
        });

        // 确保事件成功派发
        const dispatched = window.dispatchEvent(event);
        if (!dispatched) {
          console.error('选集切换事件派发失败');
        }
      } else {
        console.error('选集信息不完整或URL为空:', index, episode);
      }
    }

    // 如果是抽屉模式，点击后关闭抽屉
    if (isDrawerOpen) {
      closeDrawer();
    }
    
    // 清除当前可能存在的焦点状态
    if (document.activeElement instanceof HTMLElement) {
      document.activeElement.blur();
    }
  }, [videoId, isDrawerOpen, playList, closeDrawer, onEpisodeChange]);

  // 切换排序方向
  const toggleSort = useCallback(() => {
    // 设置来自排序的标识
    setIsFromSort(true);
    // 设置不进行滚动
    setShouldScroll(false);
    // 改变排序方向
    setIsReversed(prev => !prev);

    // 等待排序完成后再滚动到最左侧
    requestAnimationFrame(() => {
      // 滚动到最左侧
      if (scrollContainerRef.current) {
        const container = scrollContainerRef.current;
        if (container) {
          container.scrollTo({
            left: 0,
            behavior: 'smooth' // 使用smooth来实现平滑过渡
          });
        }
      }

      // 使用setTimeout确保滚动动画完成后再恢复滚动行为
      setTimeout(() => {
        setShouldScroll(true);
        setIsFromSort(false);
      }, 500); // 给足够的时间让滚动动画完成
    });
  }, []);

  // 滚动到选中的选集
  useEffect(() => {
    // 滚动水平选集列表到选中位置
    if (activeItemRef.current && scrollContainerRef.current) {
      // 增加延迟时间，确保布局完全渲染
      setTimeout(() => {
        const container = scrollContainerRef.current;
        const item = activeItemRef.current;
        if (container && item) {
          const containerWidth = container.offsetWidth;
          const itemWidth = item.offsetWidth;

          // 修改滚动位置计算，确保选中项更靠近中间位置
          // 获取选中项的绝对位置
          const itemLeft = item.getBoundingClientRect().left;
          const containerLeft = container.getBoundingClientRect().left;

          // 计算相对于容器的位置
          const relativePosition = itemLeft - containerLeft;

          // 计算应该滚动的距离，确保选中项居中
          const scrollLeft = container.scrollLeft + relativePosition - (containerWidth / 2) + (itemWidth / 2);

          // 确保计算的位置有效
          if (!isNaN(scrollLeft) && scrollLeft >= 0) {
            container.scrollTo({ left: scrollLeft, behavior: 'smooth' });
          }
        }
      }, 800); // 恢复延迟到800ms
    }
  }, [localCurrentIndex]);

  // 处理抽屉打开时滚动到选中选集
  useEffect(() => {
    if (!shouldScroll || isFromSort) return;

    if (isDrawerOpen && localCurrentIndex !== undefined) {
      // 延迟确保抽屉动画完成并且DOM已渲染
      const timer = setTimeout(() => {
        // 首先滚动分组标签到可视区域
        scrollActiveGroupToCenter();
        
        // 获取当前选中的选集元素
        const selectedItem = document.querySelector(`.drawer-content .bg-red-600.text-white`);
        if (selectedItem) {
          // 使用更好的居中方式
          selectedItem.scrollIntoView({
            behavior: 'smooth',
            block: 'center'
          });

          // 可选：额外调整滚动位置优化
          const drawerContent = document.querySelector('.drawer-content .flex-1.overflow-y-auto');
          if (drawerContent) {
            const container = drawerContent as HTMLElement;
            const item = selectedItem as HTMLElement;
            const itemRect = item.getBoundingClientRect();
            const containerRect = container.getBoundingClientRect();

            // 计算一个更精确的居中位置
            const offset = itemRect.top - containerRect.top - (containerRect.height - itemRect.height) / 2;
            if (Math.abs(offset) > 10) {
              container.scrollTop = container.scrollTop + offset;
            }
          }
        }
      }, 900); // 稍微延长延迟，确保抽屉完全打开

      return () => clearTimeout(timer);
    }
  }, [isDrawerOpen, localCurrentIndex, shouldScroll, isFromSort, scrollActiveGroupToCenter]);

  // 获取水平列表中显示的列表项
  const horizontalItems = useMemo(() => {
    // 返回所有排序后的选集
    return sortedPlayList;
  }, [sortedPlayList]);

  // 处理选集组的切换
  const handleGroupChange = useCallback((groupKey: string) => {
    console.log('手动切换到分组:', groupKey);
    if (groupKey !== activeGroup) {
      // 标记用户已手动选择分组
      userSelectedGroup.current = true;
      setActiveGroup(groupKey);
    }
  }, [activeGroup]);

  // 当选集变化时重置用户选择标志
  useEffect(() => {
    userSelectedGroup.current = false;
  }, [videoId, currentPlayIndex]);

  // 当播放索引变化时，如果抽屉是打开的，更新高亮分组
  useEffect(() => {
    // 只有在抽屉打开且不是用户手动选择的情况下才自动更新分组
    if (isDrawerOpen && !userSelectedGroup.current && localCurrentIndex !== undefined) {
      // 计算在排序后列表中的索引位置
      let sortedIndex = localCurrentIndex;
      if (isReversed) {
        sortedIndex = playList.length - 1 - localCurrentIndex;
      }
      
      // 计算分组索引
      const groupIndex = Math.floor(sortedIndex / 50);
      const groupKeys = Object.keys(groupedPlaylist);
      if (groupKeys.length > 0 && groupIndex < groupKeys.length) {
        const groupKey = groupKeys[groupIndex];
        setActiveGroup(groupKey);
        console.log('播放索引变化，更新分组为:', groupKey);
      }
    }
  }, [localCurrentIndex, isDrawerOpen, isReversed, playList.length, groupedPlaylist, userSelectedGroup]);

  // 监听视频播放完毕自动切换选集事件
  useEffect(() => {
    const handleEpisodeChanged = (e: CustomEvent) => {
      const index = e.detail?.index;
      if (index !== undefined && index !== localCurrentIndex) {
        console.log('接收到选集变更事件，更新选中项:', index);
        setLocalCurrentIndex(index);
        
        // 清除当前可能存在的焦点状态
        if (document.activeElement instanceof HTMLElement) {
          document.activeElement.blur();
        }
      }
    };
    
    window.addEventListener('episodeChanged', handleEpisodeChanged as EventListener);
    
    return () => {
      window.removeEventListener('episodeChanged', handleEpisodeChanged as EventListener);
    };
  }, [localCurrentIndex]);

  // 如果只有一集，不显示选集列表
  if (totalEpisodes <= 1) return null;

  return (
    <div className="relative">

      {/* 水平滚动的选集列表 */}
      <div className="flex items-center justify-between mb-2">
        <div className="flex items-center">
          <span className="text-gray-300 text-base mr-2">选集</span>
          <span className="text-gray-400 text-base">共{totalEpisodes}集</span>
        </div>

        <div className="flex items-center">
          {/* 添加倒序按钮 */}
          <button
            onClick={toggleSort}
            className="p-1 mr-2 hover:bg-gray-700 rounded-md transition-colors flex items-center"
            title={isReversed ? "正序排列" : "倒序排列"}
          >
            <svg
              className={`w-5 h-5 text-gray-400 transition-transform ${isReversed ? 'rotate-180' : ''}`}
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M3 4h13M3 8h9m-9 4h6m4 0l4-4m0 0l4 4m-4-4v12"
              />
            </svg>
            <span className="text-sm text-gray-400 ml-1">{isReversed ? "正序" : "倒序"}</span>
          </button>

          <button
            type="button"
            onClick={openDrawer}
            className="flex items-center text-gray-300 text-base hover:text-white transition-colors px-3 py-2 rounded active:bg-gray-800"
          >
            <span className="mr-1">全部</span>
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className="h-4 w-4"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M19 9l-7 7-7-7"
              />
            </svg>
          </button>
        </div>
      </div>

      {/* 横向滚动条 */}
      <div
        ref={scrollContainerRef}
        className="flex overflow-x-auto no-scrollbar py-2 -mx-1 pb-4"
        style={{ WebkitOverflowScrolling: 'touch' }}
      >
        {horizontalItems.map((play, sortedIndex) => {
          // 计算原始索引（倒序时处理）
          const originalIndex = isReversed ? playList.length - 1 - sortedIndex : sortedIndex;
          const isActive = localCurrentIndex === originalIndex;

          return (
            <HtmlLink
              key={`scroll-${sortedIndex}`}
              ref={isActive ? activeItemRef : null}
              href={`/detail/${videoId}-${originalIndex}.html`}
              className={`flex-shrink-0 flex items-center justify-center text-center px-3 py-2 mx-1 min-w-[3rem] rounded-lg ${isActive
                ? 'bg-red-600 text-white'
                : 'bg-gray-800 text-gray-300 hover:bg-gray-700'
                }`}
              onClick={(e: React.MouseEvent<HTMLAnchorElement>) => {
                e.preventDefault(); // 阻止默认链接跳转行为
                handleEpisodeClick(originalIndex);
              }}
            >
              {play.name.replace(/第|集|话|期|期$/g, '') || (originalIndex + 1)}
            </HtmlLink>
          );
        })}
      </div>

      {/* 抽屉式选集列表 - 使用Portal渲染到body上 */}
      {isMounted && isDrawerOpen && createPortal(
        <div
          className="drawer-backdrop"
          onClick={(e) => {
            if (e.target === e.currentTarget) closeDrawer();
          }}
        >
          <div className="absolute bottom-0 left-0 right-0 flex flex-col h-[calc(100vh-18rem)]">
            <div
              ref={drawerRef}
              className="drawer-content flex flex-col h-full "
              onClick={(e) => e.stopPropagation()}
            >
              <div className="drawer-header">
                <div className="flex items-center justify-between w-full">
                  <h3 className="text-white font-medium">选集 ({totalEpisodes})</h3>

                  <div className="flex items-center">
                    {/* 抽屉中添加倒序按钮 */}
                    <button
                      onClick={toggleSort}
                      className="p-1 mr-3 hover:bg-gray-700 rounded-md transition-colors flex items-center"
                      title={isReversed ? "正序排列" : "倒序排列"}
                    >
                      <svg
                        className={`w-5 h-5 text-gray-400 transition-transform ${isReversed ? 'rotate-180' : ''}`}
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2}
                          d="M3 4h13M3 8h9m-9 4h6m4 0l4-4m0 0l4 4m-4-4v12"
                        />
                      </svg>
                    </button>

                    <button
                      type="button"
                      onClick={closeDrawer}
                      className="drawer-close"
                    >
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        className="h-6 w-6 text-gray-400"
                        fill="none"
                        viewBox="0 0 24 24"
                        stroke="currentColor"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2}
                          d="M6 18L18 6M6 6l12 12"
                        />
                      </svg>
                    </button>
                  </div>
                </div>
              </div>

              <div className="flex flex-col flex-1 pt-3 overflow-hidden">
                {/* 分组标签页 */}
                {Object.keys(groupedPlaylist).length > 1 && (
                  <div ref={groupTabsRef} className="flex overflow-x-auto no-scrollbar pb-3 px-4" style={{ WebkitOverflowScrolling: 'touch' }}>
                    {Object.keys(groupedPlaylist).map((groupKey) => {
                      // 检查此分组是否包含当前播放的集数
                      const containsCurrentEpisode = (() => {
                        if (localCurrentIndex === undefined) return false;
                        
                        // 计算当前播放的集数在排序后的索引
                        let sortedCurrentIndex = localCurrentIndex;
                        if (isReversed) {
                          sortedCurrentIndex = playList.length - 1 - localCurrentIndex;
                        }
                        
                        // 获取分组的起始和结束索引
                        const [start, end] = groupKey.split('-').map(Number);
                        const startIndex = start - 1; // 转为0基索引
                        const endIndex = Math.min(end, totalEpisodes) - 1; // 转为0基索引
                        
                        // 检查当前播放索引是否在此范围内
                        return sortedCurrentIndex >= startIndex && sortedCurrentIndex <= endIndex;
                      })();
                      
                      // 这里决定哪个标签需要高亮
                      const isActive = activeGroup === groupKey;
                      const shouldHighlight = containsCurrentEpisode && !isActive;
                      
                      return (
                        <button
                          key={groupKey}
                          // 只在真正的活动组上使用ref
                          ref={isActive ? activeGroupTabRef : null}
                          onClick={() => {
                            console.log('点击了分页按钮:', groupKey);
                            handleGroupChange(groupKey);
                          }}
                          className={`flex-shrink-0 px-3 py-1.5 mx-1 rounded-full text-sm ${
                            isActive
                              ? 'bg-red-600 text-white'
                              : (shouldHighlight ? 'bg-red-800 text-gray-100' : 'bg-gray-800 text-gray-300 hover:bg-gray-700')
                          }`}
                        >
                          {groupKey}
                        </button>
                      );
                    })}
                  </div>
                )}

                {/* 选集网格 - 使用动态计算列数 */}
                <div className="flex-1 overflow-y-auto" ref={drawerContentRef}>
                  <div className="grid gap-2 px-4 pb-2" style={{ gridTemplateColumns: `repeat(${gridCols}, 1fr)` }}>
                    {currentGroupEpisodes.map((play, groupedIndex) => {
                      // 在排序后的列表中查找该选集的索引
                      const sortedIndex = sortedPlayList.findIndex(item => item === play);
                      // 计算在原始列表中的索引
                      const originalIndex = isReversed ? playList.length - 1 - sortedIndex : sortedIndex;
                      const isActive = localCurrentIndex === originalIndex;

                      return (
                        <HtmlLink
                          key={`grid-${groupedIndex}`}
                          href={`/detail/${videoId}-${originalIndex}.html`}
                          onClick={(e: React.MouseEvent<HTMLAnchorElement>) => {
                            e.preventDefault(); // 阻止默认链接跳转
                            handleEpisodeClick(originalIndex);
                          }}
                          className={`text-center py-3 text-wrap break-words whitespace-normal px-2 rounded overflow-hidden ${isActive
                            ? 'bg-red-600 text-white'
                            : 'bg-gray-800 text-gray-300 hover:bg-gray-700'
                            }`}
                        >
                          {play.name.replace(/第|集|话|期|期$/g, '') || (originalIndex + 1)}
                        </HtmlLink>
                      );
                    })}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>,
        document.body
      )}
    </div>
  );
} 